package com.example.demo.Controller;


import com.example.demo.Dao.PersonRepository;
import com.example.demo.Dao.RecordRepository;
import com.example.demo.Entity.Person;
import com.example.demo.Qo.PersonQo;
import com.example.demo.Utils.CodeUtils;
import com.example.demo.Utils.ConstUtils;
import com.example.demo.Utils.JavaWebTokenUtils;
import com.example.demo.Utils.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.http.HttpResponse;
import java.util.Date;

@RestController
@RequestMapping("/api/wx")
@CrossOrigin
public class WxController {
    @Resource
    RecordRepository recordRepository;
    @Resource
    PersonRepository personRepository;
    @Resource
    RedisUtils redisUtils;

    private static final String CLAIM_KEY_NAME = "sub";
    private static final String CLAIM_KEY_SECRET = "WUJINGLUN";



    @GetMapping("/login")
    public CodeUtils.Message getPersonQo(String openId, HttpServletResponse
            response)
    {
        if (openId==null)
        {
            return CodeUtils.Message.builder().code(44033).message("openId不能为空").build();
        }
        Person person = personRepository.findByOpenId(openId);
        if (person == null)
        {
            return CodeUtils.Message.builder().code(44033).message("用户未注册").build();
        }
        String token;
        if (redisUtils.hasKey(person.getUsername()))
        {
            token = redisUtils.get(person.getUsername()).toString();
        }else {
            token  = Jwts.builder()
                    .claim("role",person.getAuthorities())
                    .setSubject(person.getUsername())
                    .setIssuer(CLAIM_KEY_NAME)
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24*12))
                    .signWith(SignatureAlgorithm.HS256,CLAIM_KEY_SECRET)
                    .compact();
            token = ConstUtils.TokenUtils.TOKEN_PREFIX+token;
            redisUtils.set(person.getUsername(),token,60*60*24*10);
        }
        System.out.println("小程序token："+token);
        PersonQo personQo = PersonQo.builder()
                .id(person.getId())
                .role(person.getRole())
                .realName(person.getRealName())
                .area(person.getArea())
                .openId(person.getOpenId())
                .isHealth(person.getIsHealth())
                .username(person.getUsername())
                .avatar(person.getAvatar())
                .updatedTime(person.getUpdatedTime())
                .createdTime(person.getCreatedTime()).build();
        response.setHeader("token", token);
        try {
            return   CodeUtils.Message.builder().message(new ObjectMapper().writeValueAsString(personQo)).code(20000).build();
        }catch (Exception e){
            e.printStackTrace();
            return CodeUtils.Message.builder().message("获取信息失败").code(55044).build();
        }
    }
}
